<template>
  <!-- start 管辖服务商 -->
  <div class="department-child-block">
    <div class="dept-search-group">
      <div class="dept-search-group-left">
        <el-input
          class="provider-search"
          v-model="providerKeyword"
          :placeholder="$t('department.serviceProviderTab.fetchProvider')"
          @change="fetchProvider"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <base-button
          type="primary"
          @event="manageProvider()"
          id="v-dept-step-3"
        ><i class="iconfont icon-add2" style="margin-right:6px" ></i>{{$t('department.serviceProviderTab.manageProvider')}}</base-button>
      </div>
    </div>
    <div class="department-user-table">
      <el-table
        v-table-style
        v-loading="loading"
        border
        class="team-table bbx-normal-list-box"
        :data="provider.list"
        @header-dragend="headerDragend"
        :height="tableContainerHeight"
        header-row-class-name="common-list-table-header__v2"
        stripe
      >
        <template slot="empty">
          <BaseListForNoData
            v-show="!loading"
            :notice-msg="$t('department.serviceProviderTab.emptyProvider')"
          ></BaseListForNoData>
        </template>
        <el-table-column
          v-for="column in columns"
          :key="column.field"
          :width="tableListForWidthStashprovider[column.field].width"
          show-overflow-tooltip
          :prop="column.field"
          :label="column.label">
          <template slot-scope="scope">
            <template v-if="column.field === 'providerName'">
              <div class="cur-point color-primary" @click="openDetail(scope.row.id)">{{scope.row[column.field]}}</div>
            </template>
            <template v-else>{{scope.row[column.field]}}</template>
          </template>
        </el-table-column>
        <el-table-column prop="workArea" :label="$t('common.base.operation')" width="120px" fixed="right">
          <template slot-scope="scope">
            <el-dropdown class="dropdown">
              <span class="cur-point">
                {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
                <el-dropdown-item><div @click="editProvider(scope.row)">{{$t('common.base.edit')}}</div></el-dropdown-item>
                <el-dropdown-item><div @click="delProvider(scope.row.id)">{{$t('common.base.delete')}}</div></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-footer bbx-normal-table-footer">
        <div class="list-info">
            <i18n path="common.base.table.totalCount">
              <span place="count" class="level-padding">{{ provider.total }}</span>
            </i18n>
        </div>
        <el-pagination
          class="customer-table-pagination"
          :pager-count="tenantType===0?5:7"
          background
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="provider.pageSize"
          :current-page="provider.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="provider.total"
        ></el-pagination>
      </div>
    </div>
    <modify-provider-panel 
      ref="modifyRef"
      @refresh="refreshProvider"
    ></modify-provider-panel>
  </div>
  <!-- end 管辖服务商 -->
</template>

<script>
/* components */;
import ModifyProviderPanel from '@src/modules/dept/component/ModifyProviderPanel';
/* utils */
import Page from '@model/Page';
import {storageGet as storageGetLocal, storageSet as storageSetLocal} from '@src/util/storageV2';
import { defaultTableData } from '@src/util/table'
/* api */
import {
  getProviderListByTagId,
  deleteByTagIdAndProviderId,
  saveProviderByType,
  getProviderByType
} from '@src/api/serviceProviderApi';
import platform from "@src/platform";
const pageSizeStorageKey = 'dept_depart_list';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
export default {
  name: 'service-provider-tab',
  props: {
    tenantType: {
      type: Number,
      default: 0,
    },
    tableListForWidthStashprovider: {
      type: Object,
      default: () => ({
        providerCode: {},
        providerName: {},
        contacts: {},
        providerPhone: {},
        providerType:{},
        workArea: {}
      }),
    }
  },
  components: {
    ModifyProviderPanel,
    [ModifyProviderPanel.name]: ModifyProviderPanel,
  },
  data() {
    return {
      defaultTableData,
      providerKeyword: '', // 模糊查询关键字
      columns: this.buildTableColumn(), // 表头
      provider: new Page(), // 服务商数据
      tableContainerHeight: '440px', // 表格默认高度
      loading: false,
      tagId: '', // 部门ID
    }
  },
  mounted() {
    // 读取列表的分页缓存数据
    let pageSizeStash = storageGetLocal(pageSizeStorageKey) || '';
    pageSizeStash = pageSizeStash ? JSON.parse(pageSizeStash) : {};
    if(pageSizeStash.hasOwnProperty('user')){
      this.provider['pageSize'] = pageSizeStash.provider;
    }
  },
  methods: {
    // 构建表格列
    buildTableColumn(){
      return [
        {
          label: this.$t('common.fields.providerCode.displayName_1'),
          field: 'providerCode',
        },
        {
          label: this.$t('common.fields.providerName.displayName'),
          field: 'providerName',
        },
        {
          label: this.$t('common.fields.contact.displayName'),
          field: 'contacts',
        },
        {
          label: this.$t('common.fields.phone.displayName_1'),
          field: 'providerPhone',
        },
        {
          label: this.$t('common.fields.providerType.displayName'),
          field: 'providerType',
        },
      ]
    },
    openServiceProvider(tagId, tableContainerHeight) {
      this.tagId = tagId;
      this.tableContainerHeight = tableContainerHeight;
      this.fetchProvider();
    },
    // 查询服务商
    async fetchProvider() {
      try {
        this.loading = true;
        let { pageNum, pageSize } = this.provider;
        let data = {
          pageNum,
          pageSize,
          providerName: this.providerKeyword,
          tagId: this.tagId
        }
        let res = await getProviderListByTagId(data)
        if(res.success && res.status === 0) {
          this.provider.merge(Page.as(res.data));
          this.provider['list'] = res?.data?.list || [];
        }
      } catch (e) {
        console.warn(e)
      } finally {
        this.loading = false;
      }
    },
    // 点击管理服务商
    async manageProvider() {
      try {
        // 查询已选择的服务商
        let re = await getProviderByType({objId: this.tagId, type: 0})
        if(re.status !== 0) return;
        let providers = re.data || [];
        // 选择服务商弹框
        let res = await this.$fast.select.multi.serviceProvider({
          title: this.$t('department.serviceProviderTab.selectProvider'),
          selectedServiceProviders: providers,
          max: -1
        })
        if(res.status !== 0) return;
        let paramList = res.data?.serviceProviders.map(item => {
          return {
            id: item?.id || '',
            typeId: item?.typeId || ''
          }
        })
        if(!providers.length && !paramList.length) return  //如果当前没有任务团队或人员，然后弹框也没有选择，直接返回
        let data = {
          objectId: this.tagId,
          type: 0, //（0团队1服务商）
          paramList,
        }
        this.loading = true;
        // 保存所选的服务商
        let result = await saveProviderByType(data);
        let suc = result.success && result.data;
        platform.notification({
          type: suc ? 'success' : 'error',
          title: `${this.$t('department.serviceProviderTab.addProvider')}${suc ? this.$t('common.base.success') : this.$t('common.base.fail')}`,
          message: suc ? null : result?.message
        });
        // 刷新当前页面
        this.refreshProvider();
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false;
      }
    },
    // 点击编辑服务商
    editProvider(value) {
      this.$refs.modifyRef?.open(value)
    },
    // 移除服务商从该部门中
    async delProvider(providerId) {
      try {
        if (!await this.$platform.confirm(this.$t('department.serviceProviderTab.deleteProvider'))) return;
        let data = {
          providerId,
          tagId: this.tagId
        }
        this.loading = true;
        // 调接口去移除，移除后刷新页面
        let result = await deleteByTagIdAndProviderId(data)
        let success = result.status === 0 && result.data
        this.$platform.notification({
          type: success ? 'success' : 'error',
          title: `${this.$t('department.serviceProviderTab.deletedProvider')}${success ? this.$t('common.base.success') : this.$t('common.base.fail')}`,
          message: success? null : result?.message
        });
        // 刷新当前页面
        this.refreshProvider();
      } catch (e) {
        console.warn(e)
      } finally {
        this.loading = false;
      }
    },
    // 表单拖拽钩子函数(记录下次进来column的宽度)
    headerDragend(newWidth, oldWidth, column, event) {
      this.$emit('service-header-dragend', newWidth, oldWidth, column, event)
    },
    // 页码跳转
    jump(pageNum) {
      this.provider.pageNum = pageNum;
      this.fetchProvider();
    },
    // 页数修改
    handleSizeChange(pageSize) {
      this.provider.pageSize = pageSize;
      this.provider.pageNum = 1;
      // 记录页码
      let stash_data = storageGetLocal(pageSizeStorageKey) || '';
      stash_data = stash_data ? JSON.parse(stash_data) : {};
      storageSetLocal(pageSizeStorageKey, 
        JSON.stringify({ ...stash_data,
          provider: pageSize
        }))
      // 列表查询
      this.fetchProvider();
    },
    // 跳转到服务商详情
    openDetail(tenantProviderId) {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type:PageRoutesTypeEnum.PageServiceProviderDetail,
        key:tenantProviderId,
        params:`id=${tenantProviderId}`,
        fromId
      });
    },
    // 刷新当前页面
    refreshProvider() {
      this.provider.pageNum = 1;
      this.fetchProvider();
    },
  },
}
</script>

<style scoped lang="scss">
.provider-search {
  width: 200px;
  margin-right: 12px
}
.cur-point {
  color: $color-primary-light-6;
}
.lang-select-dropdown {
  margin-top: 0!important;
}
</style>